package session

import (
	"../../../../deps/lessgo/pagelet"
	"../../../../deps/lessgo/utils"
	"../../../store"
	"strings"
	"sync"
)

var (
	locker sync.Mutex
)

type Session struct {
	AccessToken string `json:"access_token_keeper`
	Uname       string `json:"uname"`
	RemoteAddr  string `json:"remote_addr`
}

func Set(sess Session) {

	sessj, err := utils.JsonEncode(sess)
	if err == nil {
		// node := store.NodeProposal{
		// 	Key: "/sys/ids/" + sess.AccessToken,
		// 	Val: sessj,
		// }
		store.Cmd("SETEX", "sys:idss:"+sess.AccessToken, 72000, sessj)
	}
}

func IsLogin(r *pagelet.Request) bool {

	sess := Get(r)
	if sess.Uname != "" {
		return true
	}

	return false
}

func Get(r *pagelet.Request) (sess Session) {

	token, err := r.Request.Cookie("access_token_keeper")
	if err != nil {
		return
	}

	sessj := store.Cmd("GET", "sys:idss:"+token.Value).String()
	if len(sessj) < 10 {
		return
	}

	err = utils.JsonDecode(sessj, &sess)
	if err != nil {
		return
	}

	addr := "0.0.0.0"
	if addridx := strings.Index(r.RemoteAddr, ":"); addridx > 0 {
		addr = r.RemoteAddr[:addridx]
	}
	if addr != sess.RemoteAddr {
		sess.Uname = ""
		sess.RemoteAddr = ""
		return
	}

	return
}

func Del(r *pagelet.Request) {

	token, err := r.Request.Cookie("access_token_keeper")
	if err != nil || len(token.Value) < 10 {
		return
	}

	store.Cmd("DEL", "sys:idss:"+token.Value)
}
